import { Logger } from "./log.js";

const TAG = "IO";

export class FileWrapper {
  path: string;
  file: File;

  constructor(path: string, mode: string) {
    this.path = path;
    this.file = new File(path, mode);
  }

  write(data: string | ArrayBuffer | number[]) {
    this.file.write(data);
  }

  close() {
    this.file.flush();
    this.file.close();
  }
}

export const IOHelper = {
  /**
   * 追加文件，如果文件不存在，在创建？
   */
  writeData(path: string, data: string | ArrayBuffer | number[]) {
    let file = new FileWrapper(path, "a+");
    file.write(data);
    file.close();
  },

  mkdir(path: any) {
    let libc;
    try {
      libc = Process.getModuleByName("libc.so");
    } catch (e) {
      Logger.w(TAG, "libc.so not found.");
      return "-1";
    }

    var cPath = Memory.allocUtf8String(path);
    var accessPtr = libc.getExportByName("access");
    var accessFun = new NativeFunction(accessPtr, "int", ["pointer", "int"]);
    const F_OK = 0;
    if (accessFun(cPath, F_OK) == 0) {
      Logger.i(TAG, "File already exists : " + cPath);
      return 0;
    }

    var mkdirPtr = libc.getExportByName("mkdir");
    var mkdirFun = new NativeFunction(mkdirPtr, "int", ["pointer", "int"]);
    mkdirFun(cPath, 755);
  },

  chmod(path: any) {
    let libc;
    try {
      libc = Process.getModuleByName("libc.so");
    } catch (e) {
      Logger.w(TAG, "libc.so not found.");
      return;
    }

    var chmodPtr = libc.getExportByName("chmod");
    var chmodFun = new NativeFunction(chmodPtr, "int", ["pointer", "int"]);

    var cPath = Memory.allocUtf8String(path);
    chmodFun(cPath, 755);
  },
} as const;
